import jwt
from flask import jsonify

class Myjwt:
    def __init__(self) -> None:
        self.secretkey = 'yictuvyibojp'

    # 加密
    def jwt_encode(self, data):
        token = jwt.encode(data, self.secretkey, algorithm='HS256')
        return token

    # 解密
    def jwt_decode(self, token):
        if not token:
            return jsonify({
                'code': 400,
                'msg': "token未获取"
            })
        try:
            token = jwt.decode(token, self.secretkey, algorithms='HS256')
        except Exception as e:
            print(e)
            return jsonify({
                'code': 403,
                'msg': "用户未登录"
            })
        return token

    # 对比
    def check(self, token):
        try:
            # 解密传过来的token信息
            mes = self.jwt_decode(token)
        except:
            return False
        # 生成一个新的token
        nwetoken = self.jwt_encode(mes)
        # 判断传过来的token和新生成的token是否一致
        if nwetoken == token:
            return True
        else:
            return False


myjwt = Myjwt()